package thread;

import java.util.PriorityQueue;

class MyTimerTask3 implements Comparable<MyTimerTask3>{
    private Runnable runnable;
    private long time;
    public MyTimerTask3(Runnable runnable, long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public void run(){
        runnable.run();
    }

    public long getTime(){
        return time;
    }

    @Override
    public int compareTo(MyTimerTask3 o) {
        return (int) (this.time - o.time);
    }
}

class MyTimer3{
    private Object locker = new Object();
    private Thread t = null;
    private PriorityQueue<MyTimerTask3> queue = new PriorityQueue<>();
    public MyTimer3(){
        t = new Thread(() ->{
           while(true){
               synchronized (locker){
                   try{
                       while(queue.isEmpty()){
                           locker.wait();
                       }
                       MyTimerTask3 task3 = queue.peek();
                       long curTime = System.currentTimeMillis();
                       if(curTime >= task3.getTime()){
                           queue.poll();
                           task3.run();
                       } else {
                           locker.wait(task3.getTime() - curTime);
                       }
                   } catch (InterruptedException e){
                       e.printStackTrace();
                   }
               }
           }
        });
        t.start();
    }
    public void schedule(Runnable runnable,long delay){
        synchronized(locker){
            MyTimerTask3 task3 = new MyTimerTask3(runnable,delay);
            queue.offer(task3);
            locker.notify();
        }
    }
}

public class ThreadDemo31 {
    public static void main(String[] args) {
        MyTimer3 timer3 = new MyTimer3();
        timer3.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        },3000);
        timer3.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        },2000);
        timer3.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        },1000);
        System.out.println("hello main");
    }
}
